<template>
  <div v-loading="loading" class="container">

    <el-form ref="form" :inline="true" label-position="left" size="mini">

      <el-form-item label="Instance:">
        <el-select
          v-model="dbSelectCondition"
          style="min-width: 260px"
          clearable
          filterable
          placeholder="请选择"
        >
          <el-option
            v-for="item in dbSelecteds"
            :key="item.instance"
            :label="item.instance"
            :value="item.instance"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="查询时间:">
        <el-date-picker
          v-model="timeRange"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="timestamp"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
          :editable="false"
          @change="timeRangeOnChange"
        />
      </el-form-item>

      <el-form-item label="查询间隔:">
        <el-select
          v-model="timeSelectCondition"
          style="min-width: 260px"
          clearable
          filterable
          placeholder="请选择"
          @change="reloadRefreshTimer"
        >
          <el-option
            v-for="item in timeSelecteds"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="自动刷新:">
        <el-switch
          v-model="autoRefresh"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
      </el-form-item>

    </el-form>

    <el-card shadow="always">
      <div class="status-card-container">
        <div v-for="(item, index) in osStatus" :key="index" class="status-card">
          <div class="top-card-title">{{ item.label }}</div>
          <div class="top-card-detail">{{ item.value }}</div>
        </div>
      </div>
    </el-card>

    <el-collapse v-model="collapseActiveNames" style="margin-top: 20px">
      <el-collapse-item title="CPU" name="1">
        <div class="nineGridContainer">
          <el-card class="nineGrid" style="width: calc(300% + 20px)" shadow="always">
            <div class="card-header-title">CPU使用率</div>
            <el-divider />
            <lineChart class="lineChart" :chart-option="cpuUsageRateChartOption" />
          </el-card>
          <div />
          <div />
        </div>
      </el-collapse-item>

      <el-collapse-item title="内存" name="2">
        <div class="nineGridContainer">
          <el-card class="nineGrid" style="width: calc(300% + 20px)" shadow="always">
            <div class="card-header-title">内存信息</div>
            <el-divider />
            <lineChart class="lineChart" :chart-option="memoryChartOption" />
          </el-card>
        </div>
      </el-collapse-item>

      <el-collapse-item title="磁盘" name="3">
        <div class="nineGridContainer">
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">磁盘使用率</div>
            <el-divider />
            <lineChart class="lineChart" :chart-option="nodeFilesystemUsedRateChartOption" />
          </el-card>

          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">每秒磁盘读写容量</div>
            <el-divider />
            <lineChart class="lineChart" :chart-option="nodeDiskAccessingChartOption" />
          </el-card>

          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">磁盘读写速率（IOPS）</div>
            <el-divider />
            <lineChart class="lineChart" :chart-option="nodeDiskAccessingCompletedRateChartOption" />
          </el-card>
        </div>
      </el-collapse-item>

      <el-collapse-item title="网络" name="4">
        <div class="nineGridContainer">
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">每秒网络宽带使用</div>
            <el-divider />
            <lineChart class="lineChart" :chart-option="networkChartOption" />
          </el-card>
          <el-card class="nineGrid" style="width: calc(200% + 10px)" shadow="always">
            <div class="card-header-title">网络Socket连接信息</div>
            <el-divider />
            <lineChart class="lineChart" :chart-option="nodeSocketChartOption" />
          </el-card>
          <div />
        </div>
      </el-collapse-item>

      <el-collapse-item title="系统负载" name="5">
        <div class="nineGridContainer">
          <el-card class="nineGrid" style="width: calc(300% + 20px)" shadow="always">
            <div class="card-header-title">系统平均负载</div>
            <el-divider />
            <lineChart class="lineChart" :chart-option="avgLoadChartOption" />
          </el-card>
          <div />
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script>

import { query, series, query_range } from '../../../api/prometheus'
import { formatSeconds, bytesToSize, stringToPercent, bytesToSizeSecondsRate, stringFoFixed2 } from '../../../utils/index'
import lineChart from '../../../components/echarts/vue-chart'
import { lineChartOption } from '../../../utils/echart-ori-options'
import { pickerOptions } from '../../../utils/date_time_picker_options'
import moment from 'moment'
import { setInterval, clearInterval } from 'timers'

export default {
  components: { lineChart },
  filters: {
    percentageFilter: function(value) {
      if (!value) {
        return ''
      }
      return Math.round(value * 100) / 100.0 + '%'
    }
  },
  data() {
    return {
      dbSelecteds: [],
      dbSelectCondition: undefined,
      collapseActiveNames: ['1'],
      timeSelecteds: [
        { label: '1s', value: '1s' },
        { label: '5s', value: '5s' },
        { label: '10s', value: '10s' },
        { label: '30s', value: '30s' },
        { label: '1m', value: '1m' },
        { label: '2m', value: '2m' },
        { label: '3m', value: '3m' },
        { label: '5m', value: '5m' },
        { label: '10m', value: '10m' },
        { label: '30m', value: '30m' }
      ],
      timeSelectedToMs: {
        '1s': 1000,
        '5s': 5000,
        '10s': 10000,
        '30s': 30000,
        '1m': 60000,
        '2m': 120000,
        '3m': 180000,
        '5m': 300000,
        '10m': 6000000,
        '30m': 18000000
      },
      timeSelectCondition: '2m',
      pickerOptions: pickerOptions,
      timeRange: [],
      autoRefresh: false,
      osStatus: [
        { label: '运行时间', value: '' },
        { label: 'CPU 核数', value: '' },
        { label: '总内存', value: '' },
        { label: '5m负载', value: '' },
        { label: 'CPU使用率', value: '' },
        { label: '内存使用率', value: '' },
        { label: '分区使用率', value: '' },
        { label: '连接数', value: '' },
        { label: 'TCP_tw', value: '' },
        { label: '磁盘读取', value: '' },
        { label: '磁盘写入', value: '' },
        { label: '下载带宽', value: '' },
        { label: '上传带宽', value: '' }
      ],
      loading: false,
      refreshTimer: undefined,
      memoryChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      cpuUsageRateChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      networkChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      avgLoadChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      nodeDiskAccessingChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      nodeDiskAccessingCompletedRateChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      nodeFilesystemUsedRateChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      nodeSocketChartOption: JSON.parse(JSON.stringify(lineChartOption))
    }
  },
  watch: {
    dbSelectCondition(value) {
      this.reloadRequest()
    },
    timeSelectCondition(value) {
      this.reloadRequest()
    }
  },
  beforeDestroy() {
    this.clearRefreshTimer()
  },
  mounted() {
    this.timeRange = [moment().add(-1, 'h').format('x'), moment().format('x')]
    //  CPU使用率
    this.cpuUsageRateChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${stringToPercent(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.cpuUsageRateChartOption.xAxis.type = 'time'
    this.cpuUsageRateChartOption.color = ['#1890FF', '#00FFFF', '#FFFF00', '#975FE4']
    this.cpuUsageRateChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.cpuUsageRateChartOption.yAxis.axisLabel.formatter = '{value} %'
    this.cpuUsageRateChartOption.legend.data = ['总使用率', '用户使用率', '系统使用率', '磁盘IO使用率']
    this.cpuUsageRateChartOption.series = [
      {
        name: '总使用率',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: '用户使用率',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: '系统使用率',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: '磁盘IO使用率',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    //  内存信息
    this.memoryChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${bytesToSize(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 50)
      return 'loading...'
    }
    this.memoryChartOption.xAxis.type = 'time'
    this.memoryChartOption.grid.left = 60
    this.memoryChartOption.color = ['#FE2E2E', '#01DF01', '#1890FF']
    this.memoryChartOption.yAxis.axisLabel.formatter = function(value, index) {
      return bytesToSize(value)
    }
    this.memoryChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.memoryChartOption.legend.data = ['总内存', '可用', '已用']
    this.memoryChartOption.series = [
      {
        name: '总内存',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: '可用',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: '已用',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    //  网络信息
    this.networkChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${bytesToSizeSecondsRate(param.value[1]).replace('-', '')}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 50)
      return 'loading...'
    }
    this.networkChartOption.xAxis.type = 'time'
    this.networkChartOption.grid.left = 60
    this.networkChartOption.color = ['#01DF01', '#FFFF00']
    this.networkChartOption.yAxis.axisLabel.formatter = function(value, index) {
      return bytesToSizeSecondsRate(value)
    }
    this.networkChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.networkChartOption.legend.data = ['eth0_out上传', 'eth0_in下载']
    this.networkChartOption.series = [
      {
        name: 'eth0_out上传',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'eth0_in下载',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    //  系统平均负载
    this.avgLoadChartOption.xAxis.type = 'time'
    this.avgLoadChartOption.grid.left = 60
    this.avgLoadChartOption.color = ['#FE2E2E', '#01DF3A', '#FFFF00']
    this.avgLoadChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.avgLoadChartOption.legend.data = ['15分钟负载', '5分钟负载', '1分钟负载']
    this.avgLoadChartOption.series = [
      {
        name: '15分钟负载',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: '5分钟负载',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: '1分钟负载',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    //  每秒磁盘读写容量
    this.nodeDiskAccessingChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${bytesToSizeSecondsRate(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 50)
      return 'loading...'
    }
    this.nodeDiskAccessingChartOption.xAxis.type = 'time'
    this.nodeDiskAccessingChartOption.grid.left = 60
    this.nodeDiskAccessingChartOption.color = ['#DF0101', '#1890FF']
    this.nodeDiskAccessingChartOption.yAxis.axisLabel.formatter = function(value, index) {
      return bytesToSizeSecondsRate(value)
    }
    this.nodeDiskAccessingChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.nodeDiskAccessingChartOption.legend.data = ['vda_写入', 'vda_读取']
    this.nodeDiskAccessingChartOption.series = [
      {
        name: 'vda_写入',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'vda_读取',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    //  磁盘读写速率
    this.nodeDiskAccessingCompletedRateChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${stringFoFixed2(param.value[1])} io/s</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 50)
      return 'loading...'
    }
    this.nodeDiskAccessingCompletedRateChartOption.xAxis.type = 'time'
    this.nodeDiskAccessingCompletedRateChartOption.grid.left = 60
    this.nodeDiskAccessingCompletedRateChartOption.color = ['#04B404', '#81F7F3']
    this.nodeDiskAccessingCompletedRateChartOption.yAxis.axisLabel.formatter = function(value, index) {
      return value + ' io/s'
    }
    this.nodeDiskAccessingCompletedRateChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.nodeDiskAccessingCompletedRateChartOption.legend.data = ['vda_写入', 'vda_读取']
    this.nodeDiskAccessingCompletedRateChartOption.series = [
      {
        name: 'vda_写入',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'vda_读取',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    //  磁盘使用率
    this.nodeFilesystemUsedRateChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${stringToPercent(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.nodeFilesystemUsedRateChartOption.xAxis.type = 'time'
    this.nodeFilesystemUsedRateChartOption.color = ['#04B404']
    this.nodeFilesystemUsedRateChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.nodeFilesystemUsedRateChartOption.yAxis.axisLabel.formatter = '{value} %'
    this.nodeFilesystemUsedRateChartOption.legend.data = ['使用率']
    this.nodeFilesystemUsedRateChartOption.series = [
      {
        name: '使用率',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false
      }
    ]

    //  网络Socket连接信息
    this.nodeSocketChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${stringFoFixed2(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.nodeSocketChartOption.xAxis.type = 'time'
    this.nodeSocketChartOption.grid.left = 60
    this.nodeSocketChartOption.grid.right = 130
    this.nodeSocketChartOption.legend = {
      icon: 'pin',
      padding: 5,
      itemWidth: 10,
      itemHeight: 5,
      itemGap: 10,
      right: 0,
      top: '0',
      orient: 'vertical',
      textStyle: {
        fontSize: 12
      }
    }
    this.nodeSocketChartOption.color = ['#FE2E2E', '#1890FF', '#FF8000', '#01DF3A', '#FFFF00', '#FE2EF7', '#58ACFA', '#6A0888']
    this.nodeSocketChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.nodeSocketChartOption.legend.data = ['Sockets_used', 'TCP_alloc', 'UDP_inuse', 'CurrEstab', 'TCP_tw', 'Tcp_OutSegs', 'Tcp_InSegs', 'Tcp_RetransSegs']
    this.nodeSocketChartOption.series = [
      {
        name: 'Sockets_used',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'TCP_alloc',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'UDP_inuse',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'CurrEstab',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'TCP_tw',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Tcp_OutSegs',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Tcp_InSegs',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Tcp_RetransSegs',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    this.nodesInfo()
  },

  methods: {
    timeRangeOnChange() {
      if (this.timeRange && this.timeRange.length > 1) {
        this.reloadRequest()
      }
    },
    nodesInfo() {
      series({ 'match[]': 'node_uname_info{origin_prometheus=~"",job=~"node"}' }).then(res => {
        this.dbSelecteds = res.data.data
        this.dbSelectCondition = this.dbSelecteds[0].instance
      })
    },
    reloadRefreshTimer() {
      console.log('执行', this.timeSelectedToMs[this.timeSelectCondition])
      this.clearRefreshTimer()
      this.refreshTimer = setInterval(() => {
        if (this.autoRefresh) {
          this.timeRange = [moment().add(-1, 'h').format('x'), moment().format('x')]
          this.reloadRequest()
        }
        console.log('执行')
      }, this.timeSelectedToMs[this.timeSelectCondition])
    },
    clearRefreshTimer() {
      console.log('清除')
      clearInterval(this.refreshTimer)
      this.refreshTimer = null
    },
    reloadRequest() {
      if (!this.dbSelectCondition) {
        return
      }
      this.queryRequest(`time() - node_boot_time_seconds{origin_prometheus=~"",job=~"node", instance=~"${this.dbSelectCondition}"}`).then(res => {
        this.osStatus[0].value = formatSeconds(res) || ''
      })
      this.queryRequest(`count(node_cpu_seconds_total{origin_prometheus=~"",job=~"node", mode='system', instance=~"${this.dbSelectCondition}"})`).then(res => {
        this.osStatus[1].value = res
      })
      this.queryRequest(`node_memory_MemTotal_bytes{origin_prometheus=~"",job=~"node", instance=~"${this.dbSelectCondition}"} - 0`).then(res => {
        this.osStatus[2].value = bytesToSize(res) || ''
      })
      this.queryRequest(`node_load5{origin_prometheus=~"",job=~"node", instance=~"${this.dbSelectCondition}"}`).then(res => {
        this.osStatus[3].value = res
      })
      this.queryRequest(`(1 - avg(rate(node_cpu_seconds_total{origin_prometheus=~"",job=~"node",mode="idle", instance=~"${this.dbSelectCondition}"}[${this.timeSelectCondition}]))) * 100`).then(res => {
        this.osStatus[4].value = stringToPercent(res)
      })
      this.queryRequest(`(1 - (node_memory_MemAvailable_bytes{origin_prometheus=~"",job=~"node"} / (node_memory_MemTotal_bytes{origin_prometheus=~"",job=~"node", instance=~"${this.dbSelectCondition}"})))* 100`).then(res => {
        this.osStatus[5].value = stringToPercent(res)
      })
      this.queryRequest(`max((node_filesystem_size_bytes{origin_prometheus=~"",job=~"node",instance=~"${this.dbSelectCondition}",fstype=~"ext.?|xfs"}-node_filesystem_free_bytes{origin_prometheus=~"",job=~"node",instance=~"${this.dbSelectCondition}",fstype=~"ext.?|xfs"}) *100/(node_filesystem_avail_bytes {origin_prometheus=~"",job=~"node",instance=~"${this.dbSelectCondition}",fstype=~"ext.?|xfs"}+(node_filesystem_size_bytes{origin_prometheus=~"",job=~"node",instance=~"${this.dbSelectCondition}",fstype=~"ext.?|xfs"}-node_filesystem_free_bytes{origin_prometheus=~"",job=~"node",instance=~"${this.dbSelectCondition}",fstype=~"ext.?|xfs"})))by(instance)`).then(res => {
        this.osStatus[6].value = stringToPercent(res)
      })
      this.queryRequest(`node_netstat_Tcp_CurrEstab{origin_prometheus=~"",job=~"node",instance=~"${this.dbSelectCondition}"} - 0`).then(res => {
        this.osStatus[7].value = res
      })
      this.queryRequest(`node_sockstat_TCP_tw{origin_prometheus=~"",job=~"node",instance=~"${this.dbSelectCondition}"} - 0`).then(res => {
        this.osStatus[8].value = res
      })
      this.queryRequest(`max(rate(node_disk_read_bytes_total{origin_prometheus=~"",job=~"node",instance=~"${this.dbSelectCondition}"}[${this.timeSelectCondition}])) by (instance)`).then(res => {
        this.osStatus[9].value = bytesToSizeSecondsRate(res)
      })

      this.queryRequest(`max(rate(node_disk_written_bytes_total{origin_prometheus=~"",job=~"node",instance=~"${this.dbSelectCondition}"}[${this.timeSelectCondition}])) by (instance)`).then(res => {
        this.osStatus[10].value = bytesToSizeSecondsRate(res)
      })

      this.queryRequest(`max(rate(node_network_receive_bytes_total{origin_prometheus=~"",job=~"node",instance=~"${this.dbSelectCondition}"}[${this.timeSelectCondition}]) *8) by (instance)`).then(res => {
        this.osStatus[11].value = bytesToSizeSecondsRate(res)
      })

      this.queryRequest(`max(rate(node_network_transmit_bytes_total{origin_prometheus=~"",job=~"node",instance=~"${this.dbSelectCondition}"}[${this.timeSelectCondition}]) *8) by (instance)`).then(res => {
        this.osStatus[12].value = bytesToSizeSecondsRate(res)
      })

      this.queryRangeRequest(`(1 - avg(rate(node_cpu_seconds_total{instance=~"${this.dbSelectCondition}",mode="idle"}[${this.timeSelectCondition}])) by (instance))*100`).then(res => {
        this.cpuUsageRateChartOption.series[0].data = res
      })
      this.queryRangeRequest(`avg(rate(node_cpu_seconds_total{instance=~"${this.dbSelectCondition}",mode="user"}[${this.timeSelectCondition}])) by (instance) *100`).then(res => {
        this.cpuUsageRateChartOption.series[1].data = res
      })
      this.queryRangeRequest(`avg(rate(node_cpu_seconds_total{instance=~"${this.dbSelectCondition}",mode="system"}[${this.timeSelectCondition}])) by (instance) *100`).then(res => {
        this.cpuUsageRateChartOption.series[2].data = res
      })
      this.queryRangeRequest(`avg(rate(node_cpu_seconds_total{instance=~"${this.dbSelectCondition}",mode="iowait"}[${this.timeSelectCondition}])) by (instance) *100`).then(res => {
        this.cpuUsageRateChartOption.series[3].data = res
      })

      this.queryRangeRequest(`node_memory_MemTotal_bytes{instance=~"${this.dbSelectCondition}"}`).then(res => {
        this.memoryChartOption.series[0].data = res
      })

      this.queryRangeRequest(`node_memory_MemTotal_bytes{instance=~"${this.dbSelectCondition}"} - node_memory_MemAvailable_bytes{instance=~"${this.dbSelectCondition}"}`).then(res => {
        this.memoryChartOption.series[1].data = res
      })

      this.queryRangeRequest(`node_memory_MemAvailable_bytes{instance=~"${this.dbSelectCondition}"}`).then(res => {
        this.memoryChartOption.series[2].data = res
      })

      this.queryRangeRequest(`rate(node_network_receive_bytes_total{instance=~'${this.dbSelectCondition}',device=~"eth0"}[10m])*8`).then(res => {
        this.networkChartOption.series[0].data = res
      })

      this.queryRangeRequest(`rate(node_network_transmit_bytes_total{instance=~'${this.dbSelectCondition}',device=~"eth0"}[10m])*8`, true).then(res => {
        var results = []
        for (let i = 0; i < res.length; i++) {
          const value = res[i]
          results.push([value[0] * 1000, -value[1]])
        }
        this.networkChartOption.series[1].data = results
      })

      this.queryRangeRequest(`node_load15{instance=~"${this.dbSelectCondition}"}`).then(res => {
        this.avgLoadChartOption.series[0].data = res
      })
      this.queryRangeRequest(`node_load5{instance=~"${this.dbSelectCondition}"}`).then(res => {
        this.avgLoadChartOption.series[1].data = res
      })
      this.queryRangeRequest(`node_load1{instance=~"${this.dbSelectCondition}"}`).then(res => {
        this.avgLoadChartOption.series[2].data = res
      })
      this.queryRangeRequest(`rate(node_disk_read_bytes_total{instance=~"${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.nodeDiskAccessingChartOption.series[0].data = res
      })
      this.queryRangeRequest(`rate(node_disk_written_bytes_total{instance=~"${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.nodeDiskAccessingChartOption.series[1].data = res
      })

      this.queryRangeRequest(`rate(node_disk_reads_completed_total{instance=~"${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.nodeDiskAccessingCompletedRateChartOption.series[0].data = res
      })
      this.queryRangeRequest(`rate(node_disk_writes_completed_total{instance=~"${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.nodeDiskAccessingCompletedRateChartOption.series[1].data = res
      })

      this.queryRangeRequest(`(node_filesystem_size_bytes{instance=~'${this.dbSelectCondition}',fstype=~"ext.*|xfs",mountpoint !~".*pod.*"}-node_filesystem_free_bytes{instance=~'${this.dbSelectCondition}',fstype=~"ext.*|xfs",mountpoint !~".*pod.*"}) *100/(node_filesystem_avail_bytes {instance=~'${this.dbSelectCondition}',fstype=~"ext.*|xfs",mountpoint !~".*pod.*"}+(node_filesystem_size_bytes{instance=~'${this.dbSelectCondition}',fstype=~"ext.*|xfs",mountpoint !~".*pod.*"}-node_filesystem_free_bytes{instance=~'${this.dbSelectCondition}',fstype=~"ext.*|xfs",mountpoint !~".*pod.*"}))`).then(res => {
        this.nodeFilesystemUsedRateChartOption.series[0].data = res
      })

      this.queryRangeRequest(`node_sockstat_sockets_used{instance=~'${this.dbSelectCondition}'}`).then(res => {
        this.nodeSocketChartOption.series[0].data = res
      })
      this.queryRangeRequest(`node_sockstat_TCP_alloc{instance=~'${this.dbSelectCondition}'}`).then(res => {
        this.nodeSocketChartOption.series[1].data = res
      })
      this.queryRangeRequest(`node_sockstat_UDP_inuse{instance=~'${this.dbSelectCondition}'}`).then(res => {
        this.nodeSocketChartOption.series[2].data = res
      })
      this.queryRangeRequest(`node_netstat_Tcp_CurrEstab{instance=~'${this.dbSelectCondition}'}`).then(res => {
        this.nodeSocketChartOption.series[3].data = res
      })
      this.queryRangeRequest(`node_sockstat_TCP_tw{instance=~'${this.dbSelectCondition}'}`).then(res => {
        this.nodeSocketChartOption.series[4].data = res
      })
      this.queryRangeRequest(`rate(node_netstat_Tcp_OutSegs{instance=~'${this.dbSelectCondition}'}[${this.timeSelectCondition}])`).then(res => {
        this.nodeSocketChartOption.series[5].data = res
      })
      this.queryRangeRequest(`rate(node_netstat_Tcp_InSegs{instance=~'${this.dbSelectCondition}'}[${this.timeSelectCondition}])`).then(res => {
        this.nodeSocketChartOption.series[6].data = res
      })
      this.queryRangeRequest(`rate(node_netstat_Tcp_RetransSegs{instance=~'${this.dbSelectCondition}'}[${this.timeSelectCondition}])`).then(res => {
        this.nodeSocketChartOption.series[7].data = res
      })
    },
    queryRequest(queryUrl) {
      return new Promise((resolve, reject) => {
        query({ query: queryUrl }).then(res => {
          const data = res.data.data
          console.log('data:', data)
          if (data && data.result && data.result.length > 0 && data.result[0].value) {
            resolve(data.result[0].value[1])
          } else {
            reject('queryRequest请求失败')
          }
        })
      })
    },
    queryRangeRequest(queryUrl, original = false) {
      return new Promise((resolve, reject) => {
        query_range({
          query: queryUrl,
          start: this.timeRange[0] ? this.timeRange[0] / 1000 : (new Date()).valueOf() / 1000 - 3600 * 24,
          end: this.timeRange[1] ? this.timeRange[1] / 1000 : (new Date()).valueOf() / 1000,
          step: parseInt(this.timeSelectedToMs[this.timeSelectCondition]) / 1000
        }).then(res => {
          const data = res.data.data
          console.log('data:', data)
          if (data && data.result && data.result.length > 0 && data.result[0].values) {
            const values = data.result[0].values
            if (original) {
              resolve(values)
            } else {
              var results = []
              for (let i = 0; i < values.length; i++) {
                const value = values[i]
                results.push([value[0] * 1000, value[1]])
              }
              resolve(results)
            }
          } else {
            reject('queryRangeRequest请求失败')
          }
        })
      })
    },
    gotoMonitoringServer() {
      this.$router.push({
        path: '/monitoring_server'
      })
    }
  }
}
</script>

<style scoped>
  .container>>> .el-collapse-item__header {
    background: #f9f9f9;
  }
</style>

<style lang="scss">

  .container {
    display: flex;
    flex-direction: column;
    width: 100%;
  }

  .status-card-container {
    margin: auto;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    overflow-x: auto;
  }

  .status-card {
    min-width: 80px;
    margin-right: 10px;
    display: flex;
    min-height: 50px;
    flex-direction: column;
    justify-content: flex-start;
  }

  .top-card-title {
    color: rgba(0, 0, 0, 0.45);
    font-size: 12px;
    text-align: center;
    height: 20px;
  }

  .top-card-detail {
    color: rgba(0, 0, 0, 0.85);
    font-weight: bolder;
    font-size: 18px;
    margin-top: 5px;
    text-align: center;
  }

  .card-header-title {
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
    white-space: nowrap;
    word-break: break-all;
    font-size: 18px;
  }

  .el-divider--horizontal {
    margin: 20px 0;
  }

  .el-col-5 {
    width: 20%;
  }

  .nineGridContainer {
    display: grid;
    grid-template-columns: repeat(3, 1fr); /* 相当于 1fr 1fr 1fr */
    grid-gap: 10px; /* grid-column-gap 和 grid-row-gap的简写 */
    grid-auto-flow: row;
    .nineGrid{
      background-color: #FFFFFF;
    }
    margin-top: 20px;
  }

  .lineChart {
    width: 100%;
    height: 200px;
  }

</style>
